package com.chen.authserver.v1.filter;

import com.chen.authserver.v1.service.TokenService;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@WebFilter(urlPatterns = "/v1/*")
@Order(1)
public class TokenAccessV1Filter implements Filter {

    Set<String> notFilteUri = new HashSet<>();

    ApplicationContext context = null;

    TokenService tokenService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        notFilteUri.add("/v1/sign/in");
        notFilteUri.add("/v1/sign/up");
        notFilteUri.add("/v1/notoken");
        notFilteUri.add("/v1/test");
        notFilteUri.add("/v1/illegaltoken");
        notFilteUri.add("/v1/secretkey");

        ServletContext servletContext = filterConfig.getServletContext();
        context = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        tokenService = (TokenService) context.getBean("tokenService");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String uri = httpServletRequest.getRequestURI();

        if (notFilteUri.contains(uri)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String token = httpServletRequest.getHeader("access-token");
        if (token == null) {
            httpServletResponse.sendRedirect("/v1/notoken");
        } else {
            if (tokenService.tokenValidation(token)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                httpServletResponse.sendRedirect("/v1/illegaltoken");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
